﻿/*
 * Copyright (c) 2015-2016 Constantijn Evenhuis (blueprints@const.nl)
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
using Blueprints.IO;
using Blueprints.Resolution;
using System;
using System.Reflection;

namespace Blueprints
{
    partial class BlueprintContext
    {
        private void Serialize(SerializationScope scope, object instance, Type type, string name)
        {
            if (instance == null)
            {
                scope.Nodes.Add(new StartNode(name, null, null, "null"));
                scope.Nodes.Add(new EndNode());
                return;
            }

            Type actualType = instance.GetType();
            string typeName = GetTypeName(type, actualType);

            Uri link;
            if (scope.TryGetSerializedNode(instance, out link))
            {
                link = scope.TargetUri.MakeRelativeUri(link);
                scope.Nodes.Add(new StartNode(name, typeName, null, link.ToString()));
                scope.Nodes.Add(new EndNode());
                return;
            }

            StartNode startNode = new StartNode(name, typeName, null, null);
            scope.Nodes.Add(startNode);
            TypeCategory category = TypeResolver.GetTypeCategory(actualType);
            switch (category)
            {
                case TypeCategory.NotInstantiable:
                    throw new BlueprintException("Type '" + actualType.Name + "' is not instantiable");
                case TypeCategory.Collection:
                    SerializeCollection(scope, startNode, instance, actualType);
                    break;
                case TypeCategory.Array:
                    SerializeArray(scope, startNode, instance, actualType);
                    break;
                case TypeCategory.Object:
                    SerializeObject(scope, startNode, instance, actualType);
                    break;
                case TypeCategory.Value:
                    SerializeValue(scope, startNode, instance, actualType);
                    break;
            }

            scope.Nodes.Add(new EndNode());
        }

        private void SerializeObject(SerializationScope scope, StartNode startNode, object instance, Type type)
        {
            scope.SetSerializedNode(instance, startNode);
            SerializeProperties(scope, type, instance);
        }

        private void SerializeCollection(SerializationScope scope, StartNode startNode, object instance, Type type)
        {
            scope.SetSerializedNode(instance, startNode);
            ICollectionDescriptor descriptor = TypeResolver.GetCollectionDescriptor(type);
            Type elementType = descriptor.ElementType;
            foreach (object element in descriptor.GetElements(instance))
            {
                Serialize(scope, element, elementType, "Item");
            }
        }

        private void SerializeArray(SerializationScope scope, StartNode startNode, object instance, Type type)
        {
            scope.SetSerializedNode(instance, startNode);
            IArrayDescriptor descriptor = TypeResolver.GetArrayDescriptor(type);
            Type elementType = descriptor.ElementType;
            foreach (object element in descriptor.GetElements(instance))
            {
                Serialize(scope, element, elementType, "Item");
            }
        }

        private void SerializeValue(SerializationScope scope, StartNode startNode, object instance, Type type)
        {
            string content = TypeResolver.GetValueDescriptor(type).ConvertToString(instance);
            if (type.GetTypeInfo().IsValueType || type == typeof(string))
            {
                scope.SetSerializedValue(instance, startNode, type, content);
            }
            else
            {
                scope.SetSerializedNode(instance, startNode);
            }

            scope.Nodes.Add(new ContentNode(content));
        }

        private void SerializeProperties(SerializationScope scope, Type type, object instance)
        {
            IObjectDescriptor descriptor = TypeResolver.GetObjectDescriptor(type);
            foreach (IPropertyDescriptor property in descriptor.RequiredProperties)
            {
                object value = property.GetValue(instance);
                Serialize(scope, value, property.Type, property.Name);
            }

            foreach (IPropertyDescriptor property in descriptor.OptionalProperties)
            {
                object value = property.GetValue(instance);
                if (!property.ShouldSerializeValue(instance, value))
                {
                    continue;
                }

                Serialize(scope, value, property.Type, property.Name);
            }
        }

        private string GetTypeName(Type expectedType, Type actualType)
        {
            if (actualType.Equals(expectedType))
            {
                return null;
            }
            else
            {
                return TypeResolver.GetTypeName(actualType);
            }
        }
    }
}